#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
代理配置工具
帮助设置v2rayN代理
"""

import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import socket

class ProxyConfigTool:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("代理配置工具")
        self.root.geometry("500x400")
        self.root.resizable(False, False)
        
        # 居中显示
        self.center_window()
        
        self.init_ui()
        
    def center_window(self):
        """居中显示窗口"""
        self.root.update_idletasks()
        x = (self.root.winfo_screenwidth() // 2) - (500 // 2)
        y = (self.root.winfo_screenheight() // 2) - (400 // 2)
        self.root.geometry(f"500x400+{x}+{y}")
        
    def init_ui(self):
        """初始化用户界面"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="v2rayN 代理配置工具", 
                               font=("Arial", 16, "bold"))
        title_label.pack(pady=(0, 20))
        
        # 说明文本
        desc_text = """此工具帮助您配置v2rayN代理，使Telegram群发软件能够正常连接。

使用步骤：
1. 确保v2rayN已启动并正常运行
2. 在v2rayN中开启"系统代理"
3. 点击"检测代理"按钮
4. 如果检测成功，点击"保存配置"
5. 重启Telegram群发软件"""
        
        desc_label = ttk.Label(main_frame, text=desc_text, 
                              font=("Arial", 10), justify=tk.LEFT)
        desc_label.pack(pady=(0, 20))
        
        # 代理状态框架
        status_frame = ttk.LabelFrame(main_frame, text="代理状态", padding="10")
        status_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 状态标签
        self.status_label = ttk.Label(status_frame, text="未检测", 
                                     font=("Arial", 11))
        self.status_label.pack()
        
        # 代理信息框架
        info_frame = ttk.LabelFrame(main_frame, text="代理信息", padding="10")
        info_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 代理类型
        ttk.Label(info_frame, text="代理类型:").grid(row=0, column=0, sticky=tk.W, pady=2)
        self.proxy_type_var = tk.StringVar()
        self.proxy_type_label = ttk.Label(info_frame, textvariable=self.proxy_type_var)
        self.proxy_type_label.grid(row=0, column=1, sticky=tk.W, padx=(10, 0), pady=2)
        
        # 代理地址
        ttk.Label(info_frame, text="代理地址:").grid(row=1, column=0, sticky=tk.W, pady=2)
        self.proxy_addr_var = tk.StringVar()
        self.proxy_addr_label = ttk.Label(info_frame, textvariable=self.proxy_addr_var)
        self.proxy_addr_label.grid(row=1, column=1, sticky=tk.W, padx=(10, 0), pady=2)
        
        # 代理端口
        ttk.Label(info_frame, text="代理端口:").grid(row=2, column=0, sticky=tk.W, pady=2)
        self.proxy_port_var = tk.StringVar()
        self.proxy_port_label = ttk.Label(info_frame, textvariable=self.proxy_port_var)
        self.proxy_port_label.grid(row=2, column=1, sticky=tk.W, padx=(10, 0), pady=2)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=(20, 0))
        
        # 检测代理按钮
        detect_button = ttk.Button(button_frame, text="🔍 检测代理", 
                                  command=self.detect_proxy)
        detect_button.pack(side=tk.LEFT, padx=(0, 10))
        
        # 保存配置按钮
        save_button = ttk.Button(button_frame, text="💾 保存配置", 
                                command=self.save_config)
        save_button.pack(side=tk.LEFT, padx=(0, 10))
        
        # 退出按钮
        exit_button = ttk.Button(button_frame, text="退出", 
                                command=self.root.quit)
        exit_button.pack(side=tk.RIGHT)
        
        # 初始化状态
        self.proxy_info = None
        self.update_display()
        
    def detect_proxy(self):
        """检测代理"""
        self.status_label.config(text="正在检测...")
        self.root.update()
        
        try:
            # 检测v2rayN默认端口
            v2ray_ports = [
                (10809, 'HTTP代理'),
                (10808, 'SOCKS5代理')
            ]
            
            for port, proxy_type in v2ray_ports:
                try:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.settimeout(2)
                    result = sock.connect_ex(('127.0.0.1', port))
                    sock.close()
                    
                    if result == 0:
                        # 端口开放，检测成功
                        self.proxy_info = {
                            'proxy_type': 'http' if port == 10809 else 'socks5',
                            'addr': '127.0.0.1',
                            'port': port,
                            'description': proxy_type
                        }
                        self.status_label.config(text=f"✅ 检测成功 - {proxy_type}")
                        self.update_display()
                        return
                        
                except Exception as e:
                    continue
            
            # 检测系统代理
            http_proxy = os.environ.get('HTTP_PROXY') or os.environ.get('http_proxy')
            if http_proxy:
                from urllib.parse import urlparse
                parsed = urlparse(http_proxy)
                if parsed.scheme in ['http', 'https']:
                    self.proxy_info = {
                        'proxy_type': 'http',
                        'addr': parsed.hostname,
                        'port': parsed.port or 80,
                        'description': '系统HTTP代理'
                    }
                    self.status_label.config(text="✅ 检测到系统代理")
                    self.update_display()
                    return
            
            # 没有检测到代理
            self.proxy_info = None
            self.status_label.config(text="❌ 未检测到代理")
            self.update_display()
            
        except Exception as e:
            self.status_label.config(text=f"❌ 检测失败: {str(e)}")
            self.proxy_info = None
            self.update_display()
    
    def update_display(self):
        """更新显示信息"""
        if self.proxy_info:
            self.proxy_type_var.set(self.proxy_info.get('description', '未知'))
            self.proxy_addr_var.set(self.proxy_info.get('addr', '未知'))
            self.proxy_port_var.set(str(self.proxy_info.get('port', '未知')))
        else:
            self.proxy_type_var.set("未配置")
            self.proxy_addr_var.set("未配置")
            self.proxy_port_var.set("未配置")
    
    def save_config(self):
        """保存代理配置"""
        if not self.proxy_info:
            messagebox.showwarning("警告", "请先检测代理")
            return
        
        try:
            # 读取现有配置
            config_file = "telegram_config.json"
            config = {}
            if os.path.exists(config_file):
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
            
            # 添加代理配置
            config['proxy'] = self.proxy_info
            
            # 保存配置
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            
            messagebox.showinfo("成功", f"代理配置已保存到 {config_file}\n\n重启Telegram群发软件后生效")
            
        except Exception as e:
            messagebox.showerror("错误", f"保存配置失败: {str(e)}")
    
    def run(self):
        """运行程序"""
        self.root.mainloop()

def main():
    app = ProxyConfigTool()
    app.run()

if __name__ == "__main__":
    main() 